#!/usr/bin/env python
import urllib
import urllib2
import gzip 
import cStringIO
import BeautifulSoup
import re


class Querier:
    def __init__(self):
        self.shortName = "itms"
        self.longName = "iTunes Music Store"
        self.provides = ['album_front_large', 'album_front_small', 'album_front_thumbnail']

        self.searchURL="http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZSearch.woa/wa/com.apple.jingle.search.DirectAction/advancedSearchResults?"

    def returnDataFromiTMSURL(self,url):
        req = urllib2.Request(url)

        req.add_header('User-Agent', 'User-Agent: iTunes/4.1 (Windows; U; Microsoft Windows XP Professional Service Pack 1 (Build 2600)) DPI/96')
        r= urllib2.urlopen(req)

        length=r.info().__getitem__('Content-Length')

        toDecompress = cStringIO.StringIO(r.read(int(length)))
        g = gzip.GzipFile(fileobj=toDecompress)
        data = g.read()
        return data

    def process(self,item):
        artist = item.artist
        album = item.album
        return self.queryAlbum(artist, album)

    def queryAlbum(self, artist, album):
        ret = []
        if artist is None:
            url = self.searchURL + urllib.urlencode({'albumTerm':album.encode("utf-8")})
        else:
            url = self.searchURL + urllib.urlencode({'albumTerm':album.encode("utf-8"), 'artistTerm':artist.encode("utf-8")})

        data = self.returnDataFromiTMSURL(url)

        soup = BeautifulSoup.BeautifulSoup(data)

        m = soup("gotourl", {'target':'main'})
        try:
            url=m[4]['url']
        except:
            return None

        data = self.returnDataFromiTMSURL(url)
        soup = BeautifulSoup.BeautifulSoup(data)

        m = soup("pictureview")
        try:
            small=m[0]['url']
            large=re.sub("170x170-99", "600x600-100", small) 
            thumb=re.sub("170x170-99", "100x100-99", small)

            ret.append(small)
            ret.append(large)
            ret.append(thumb)
        except:
            pass

        return ret
